<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2024/2/27
 * Time: 12:02
 */

namespace app\common\helper;


use app\common\enum\ConfigEnum;
use yii\helpers\ArrayHelper;

class TreeHelper extends \sookie\helpers\TreeHelper
{
    public static function generateTree(array $array){
        //第一步 构造数据
        $items = array();
        foreach($array as $value){
            $items[$value['id']] = $value;
        }
        //第二部 遍历数据 生成树状结构
        $tree = array();
        foreach($items as $key => $value){
            if(isset($items[$value['pid']])){
                if(isset($items[$value['pid']]['path_name']) && isset($items[$key]['name'])){
                    $items[$key]['path_name'] = "{$items[$value['pid']]['path_name']}-{$items[$key]['name']}";
                }
                $items[$value['pid']]['children'][] = &$items[$key];
            }else{
                if (isset($items[$key]['name'])){
                    $items[$key]['path_name'] = "{$items[$key]['name']}";
                }
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }

    //添加终端
    public static function addTreeLeaf(&$tree , $list , $tree_field , $field ,$is_clean = true){
        if($list){
            foreach ($list as $item){
                $tree = static::addTreeLeafOnce($tree,$item,$tree_field , $field);
            }
        }
        return $tree;
    }

    public static function addTreeLeafOnce(&$tree , $item ,$tree_field , $field ){
        if($tree_id = ArrayHelper::getValue($tree,$tree_field)){
            $field_id = ArrayHelper::getValue($item,$field);
            //必须是枝节点，不能是叶子
            if(empty(ArrayHelper::getValue($tree,'is_leaf'))){
                if($tree_id == $field_id){
                    if(isset($tree[ConfigEnum::EXTEND_CONFIG])){
                        $item[ConfigEnum::EXTEND_CONFIG] = $tree[ConfigEnum::EXTEND_CONFIG];
                    }
                    $item['is_leaf'] = true;
                    $tree['children'][] = $item;
                }elseif(isset($tree['children']) && $tree['children']){
                    $tree['children'] = static::addTreeLeafOnce($tree['children'],$item,$tree_field , $field);
                }
            }
        }else{
            if(is_array($tree)){
                foreach ($tree as $k => $tree_item){
                    $tree[$k] = static::addTreeLeafOnce($tree_item,$item,$tree_field , $field);
                }
            }
        }
        return $tree;
    }

    public static function clearEmptyLeaf($tree){
        return $tree;
    }
}